package com.yantong.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.yantong.enums.GroupTypeEnum;
import com.yantong.enums.MarketingGroupTypeEnum;
import com.yantong.mapper.*;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.MemberCartVo;
import com.yantong.pojo.vo.TicketVo;
import com.yantong.service.*;
import com.yantong.constant.*;
import com.yantong.exception.BDException;
import com.yantong.utils.DateUtil;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.ValidateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kanghaixin
 * @date 2018/9/25.11:22
 */
@Service
public class TicketServiceImpl implements TicketService {
	@Autowired
	private TicketMapper ticketMapper;
	@Autowired
	private ProductCentreMapper productCentreMapper;
	@Autowired
	@Lazy
	private CategoryService categoryService;
	@Autowired
	private TicketRecordMapper ticketRecordMapper;
	@Autowired
	private TicketRecordUseMapper ticketRecordUseMapper;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private StoreFreechargeMapper storeFreechargeMapper;
	@Autowired
	@Lazy
	private MemberService memberService;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private TourNumberMapper tourNumberMapper;
	@Autowired
	@Lazy
	private OrderService orderService;
	@Autowired
	private ActivityProductMapper activityProductMapper;
	@Autowired
	private ActivityMapper activityMapper;
	@Autowired
	private MarketingGroupMapper marketingGroupMapper;
	@Autowired
	private WxNotifyService wxNotifyService;
	@Autowired
	private IndustryBrandService industryBrandService;
	@Autowired
	private OrderSplitInfoMapper orderSplitInfoMapper;
	@Autowired
	private JuheOrderMapper juheOrderMapper;

	@Value("${Applet.TemplatemsgCreateUserUrl}")
	private String templatemsgCreateUserUrl;
	private static final Logger logger = LoggerFactory.getLogger(TicketServiceImpl.class);

	@Override
	public PageUtils<Ticket> listTickets(String queryItem, Long centreId, Integer status, int offset, int limit) {
		return listTickets(queryItem, centreId, null, status, offset, limit);
	}

	@Override
	public PageUtils<Ticket> listTickets(String queryItem, Long centreId, Long teamId, Integer status, Integer activityType, Long activityId, Integer usableFlag, int offset, int limit) {
		PageUtils<Ticket> pageUtils = new PageUtils<>();
		Map<String, Object> params = new HashMap<>();

		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (teamId != null) {
			params.put("teamId", teamId);
		}
		if (activityId != null) {
			params.put("activityId", activityId);
		}
		if (activityType != null) {
			params.put("activityType", activityType);
		}
		if (usableFlag != null) {
			params.put("usableFlag", usableFlag);
		}
		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		if (status != null) {
			params.put("isInvalid", status);
		}
		params.put("del", 0);

		int total = ticketMapper.count(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(ticketMapper.queryTickerList(params, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	public PageUtils<Ticket> listByFreecharge(String queryItem, Long centreId, Long teamId, Integer status, Integer activityType, Long activityId, int offset, int limit) {
		PageUtils<Ticket> pageUtils = new PageUtils<>();
		Map<String, Object> params = new HashMap<>();

		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (teamId != null) {
			params.put("freeTeamId", teamId);
		}
		if (activityId != null) {
			params.put("activityId", activityId);
		}
		if (activityType != null) {
			params.put("activityType", activityType);
		}

		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		if (status != null) {
			params.put("isInvalid", status);
		}
		params.put("del", 0);

		int total = ticketMapper.count(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(ticketMapper.queryTickerListByFreeCharge(params, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	public void writeOffTicketList(Member member, TicketParam ticketParam) {
		if (ValidateUtil.isNotEmptyCollection(ticketParam.getIdList())) {
			for (Long id : ticketParam.getIdList()) {
				ticketParam.setId(id);
				ticketParam.setCountUse(1);
				writeOffTicket(member, ticketParam);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int writeOffTicket(Member member, TicketParam ticketParam) {
		if (null == member) {
			throw new BDException("用户信息异常，请重试");
		}
		TicketRecord ticket = ticketRecordMapper.selectByPrimaryKey(ticketParam.getId());

		if (null == ticket) {
			throw new BDException("优惠券信息异常，请重试");
		}

		Ticket ticketResult = ticketMapper.selectByPrimaryKey(ticket.getTicketId());

		if (ticketResult == null) {
			throw new BDException("优惠券信息异常，请重试");
		}

		if (ticket.getTeamId() == null || !ticket.getTeamId().equals(member.getTeamid())) {
			throw new BDException("优惠券不属于该门店");
		}

		if (ticketParam.getCountUse() == null || ticketParam.getCountUse() == 0) {
			throw new BDException("请输入核销优惠券数量");
		}
        /*if (member.getId() != ticket.getMid()) {
            throw new BDException("优惠券所属用户信息异常，请重试");
        }*/

		if (ticket.getCount() < ticketParam.getCountUse() + ticket.getCountUsed()) {
			logger.info("==ticketParam.getId()==" + ticketParam.getId() + "==ticket.getCount()==" + ticket.getCount() + "==ticketParam.getCountUse()==" + ticketParam.getCountUse() + "==ticket.getCountUsed()==" + ticket.getCountUsed());
			throw new BDException("优惠券剩余数量不足，仅剩" + (ticket.getCount() - ticket.getCountUsed()) + "张");
		}

		//优惠券的使用张数增加
		ticket.setCountUsed(ticket.getCountUsed() + ticketParam.getCountUse());
		//优惠券使用完,状态设置为已使用
		if (ticket.getCountUsed() >= ticket.getCount()) {
			ticket.setStatus(TicketStatus.USED.getStatus());
		}

		TicketRecordUse ticketRecordUse = new TicketRecordUse();
		ticketRecordUse.setVerifyMid(member.getId());
		ticketRecordUse.setVerifyMname(ValidateUtil.isNotEmptyString(member.getRealname()) ? member.getRealname() : member.getNickname());
		ticketRecordUse.setVerifyFlag(1);
		//插入使用记录
		Long ticketRecordUseId = addRecordUseInfo(ticket, ticketParam.getCountUse(), null, "优惠券核销", ticketRecordUse);

		//如果是大礼包的券释放核销相关金额
		this.settlementOrderSplitInfo(ticket, ticketRecordUseId);

		return ticketRecordMapper.updateByPrimaryKeySelective(ticket);
	}

	@Override
	public void giftPacksAfterSale(TicketRecord ticketRecord) {
		if (ticketRecord.getTicketType() != 0) {
			Order order = orderService.getByKey(ticketRecord.getOrderId());
			//如果订单不是已完成的状态则不能核销优惠券
			if (order != null) {
				if (order.getStatus() != OrderStatus.success.getCode()) {
					throw new BDException("该优惠券相关大礼包订单正在售后中，请更换其他优惠券使用！");
				}
			} else {
				JuheOrder juheOrder = juheOrderMapper.selectById(ticketRecord.getOrderId());
				if (juheOrder != null) {
					if (juheOrder.getPaystatus() != 2) {
						throw new BDException("该优惠券相关聚合支付订单正在申请退款中，请更换其他优惠券使用！");
					}
				}
			}
		}
	}

	@Override
	public void settlementOrderSplitInfo(TicketRecord ticketRecord, Long ticketRecordUseId) {
		if (ticketRecord.getTicketType() == 2) {
			this.giftPacksAfterSale(ticketRecord);
			OrderSplitInfo orderSplitInfo = orderSplitInfoMapper.selectByRefIdAndOrderIdAndStatus(ticketRecord.getTicketId(), ticketRecord.getOrderId(), 0, ticketRecord.getMid(), 1);
			logger.info("orderSplitInfo id = {},teamId = {}" , orderSplitInfo.getId() , orderSplitInfo.getTeamId());
			Member teamMember = memberService.getByKey(orderSplitInfo.getTeamId());
			if (teamMember != null && teamMember.getIsHeadOffice() == 1) {
				orderSplitInfo.setStatus(1);
				orderSplitInfo.setStatusTime(new Date());
			}
			orderSplitInfo.setVerifyFlag(1);
			orderSplitInfoMapper.updateByPrimaryKeySelective(orderSplitInfo);
			if (ticketRecordUseId != null) {
				TicketRecordUse ticketRecordUse = new TicketRecordUse();
				ticketRecordUse.setVerifyMoney(orderSplitInfo.getMoney());
				ticketRecordUse.setId(ticketRecordUseId);
				ticketRecordUseMapper.updateByPrimaryKeySelective(ticketRecordUse);
			}
//			if(orderSplitInfo.getTeamId() != null){
//				Member teamMember = memberService.getByKey(orderSplitInfo.getTeamId());
//				//商户结账  释放未结算余额
//				if(orderSplitInfo.getSplitType() == 1){
//					teamMember.setCredit2(teamMember.getCredit2().add(orderSplitInfo.getMoney()));
//					teamMember.setNoSettlementCredit2(teamMember.getNoSettlementCredit2().subtract(orderSplitInfo.getMoney()));
//
//					//余额变更记录
//					BalanceLog supplyBalanceLog = new BalanceLog();
//					supplyBalanceLog.setMid(teamMember.getId());
//					supplyBalanceLog.setMobile(teamMember.getMobile());
//					supplyBalanceLog.setRealname(teamMember.getRealname());
//					supplyBalanceLog.setStatus(0);
//					supplyBalanceLog.setType(0);
//					supplyBalanceLog.setStyle(BalanceLogStyle.PAY_PACKAGE_SETTLEMENT.getCode());
//					supplyBalanceLog.setCredittype("credit2");
//					supplyBalanceLog.setBeforeamount(teamMember.getCredit2());
//					supplyBalanceLog.setMoney(orderSplitInfo.getMoney());
//					supplyBalanceLog.setAfteramount(teamMember.getCredit2().add(orderSplitInfo.getMoney()));
//					supplyBalanceLog.setCreateTime(new Date());
//					supplyBalanceLog.setCentreId(teamMember.getCentreId());
//					supplyBalanceLog.setTitle("订单未结算余额转入");
//					supplyBalanceLog.setRemark("用户使用余额购买大礼包，送的券核销使用后结算余额");
//					supplyBalanceLog.setSource(0);
//					supplyBalanceLog.setFlowtype(BalanceLogFlowType.PAY_PACKAGE_SETTLEMENT.getCode());
//					balanceLogService.save(supplyBalanceLog);
//				}else{
//					teamMember.setSettlementMoney(teamMember.getSettlementMoney().add(orderSplitInfo.getMoney()));
//					teamMember.setNoSettlementMoney(teamMember.getNoSettlementMoney().subtract(orderSplitInfo.getMoney()));
//				}
//				memberService.updateMemberAsync(teamMember);
//				orderSplitInfo.setStatus(1);
//				orderSplitInfoMapper.updateByPrimaryKey(orderSplitInfo);
//			}
		}
	}

	@Override
	public Long addRecordUseInfo(TicketRecord ticket, Integer countUse, Long refId, String remark, TicketRecordUse ticketRecordUse) {
		if (ticketRecordUse == null) {
			ticketRecordUse = new TicketRecordUse();
		}

		BeanUtils.copyProperties(ticket, ticketRecordUse);
		ticketRecordUse.setId(null);
		ticketRecordUse.setTicketRecordId(ticket.getId());
		ticketRecordUse.setNum(countUse);
		ticketRecordUse.setRemark(remark);
		ticketRecordUse.setOrderId(refId);
		ticketRecordUseMapper.insertSelective(ticketRecordUse);
		return ticketRecordUse.getId();
	}


	@Override
	public int saveTicket(Ticket ticket) {
		if (ticket == null) {
			return 0;
		}
		ticket.setStock(ticket.getTotal());
		if (ticket.getStartTime() == null) {
			ticket.setStartTime(new Date());
		}
		return ticketMapper.insertSelective(ticket);
	}

	@Override
	public Ticket getByKey(Long ticketId) {
		if (ticketId == null) {
			return null;
		}
		Ticket ticket = ticketMapper.selectByPrimaryKey(ticketId);
		if (ticket != null) {
			String products = ticket.getProductId();
			if (StringUtils.isNotEmpty(products)) {
				List<String> productIds = Arrays.asList(products.split(","));
				String name = "";
				for (String id : productIds) {
					ProductCentre pc = null;
					try {
						pc = productCentreMapper.getByKey(Long.parseLong(id));
					} catch (NumberFormatException e) {
						logger.info("get centre product error!");
					}
					if (pc != null) {
						name = name.concat(pc.getTitle()).concat(",");
					}
				}
				ticket.setProductName(name);
			}
			Long ccate = ticket.getCcate();
			if (ccate != null) {
				Category category = categoryService.getByKey(ccate);
				if (category != null) {
					ticket.setCcateName(category.getName());
				}
			}
			//设置行业品牌名称
			Long industryBrandId = ticket.getIndustryBrandId();
			if (industryBrandId != null) {
				IndustryBrand industryBrand = industryBrandService.getIndustryBrandById(industryBrandId);
				if (industryBrand != null) {
					ticket.setIndustryBrandName(industryBrand.getName());
				}
			}
			//查询通兑券可使用门店
			if (ticket.getUsableFlag() != null && ticket.getUsableFlag() == 1) {
				if (ValidateUtil.isNotEmptyString(ticket.getUsableTeam())) {
					String[] strs = ticket.getUsableTeam().split(",");
					String[] nameStrs = new String[strs.length];
					for (int i = 0; i < strs.length; i++) {
						Member member = memberService.getByKey(Long.parseLong(strs[i]));
						if (member != null) {
							nameStrs[i] = member.gettXiaoqu();
						}
					}
					ticket.setUsableTeamName(StringUtils.join(nameStrs, ","));
				}
			}
		}
		return ticket;
	}

	@Override
	public int updateTicket(Ticket ticket) {
		if (ticket == null || ticket.getId() == null) {
			return 0;
		}

		//开始与结束时间的设置.
		Ticket ticketExit = ticketMapper.selectByPrimaryKey(ticket.getId());
		Date nowTime = new Date();
		Date startTimeExit = ticketExit.getStartTime();
		Date endTimeExit = ticketExit.getEndTime();
		Date startTime = ticket.getStartTime();
		Date endTime = ticket.getEndTime();
		if (startTime == null) {
			startTime = startTimeExit;
		}
		if (endTime == null) {
			endTime = endTimeExit;
		}

		if (ValidateUtil.isNotEmptyObjectOrString(startTime) && ValidateUtil.isNotEmptyObjectOrString(endTime)) {
			if (!startTime.before(endTime)) {
				throw new BDException("非法的开始结束时间!");
			}
		}
		if (ValidateUtil.isNotEmptyObjectOrString(endTime)) {
			if (endTime.after(nowTime)) {
				ticket.setIsInvalid(0);
			} else {
				ticket.setIsInvalid(1);
			}
		}

		//发放数量调整
		Integer numExit = ticketExit.getTotal();
		if (ValidateUtil.isNotEmptyObjectOrString(numExit)) {
			if (numExit > ticket.getTotal()) {
				throw new BDException("发放总量修改不能少于之前值!");
			}
		}

		StoreFreechargeExample example = new StoreFreechargeExample();
		example.createCriteria().andRefIdEqualTo(ticket.getId()).andTypeEqualTo(2);
		List<StoreFreecharge> storeFreecharges = storeFreechargeMapper.selectByExample(example);
		if (ValidateUtil.isNotEmptyCollection(storeFreecharges)) {
			for (StoreFreecharge s : storeFreecharges) {
				storeFreechargeMapper.deleteByPrimaryKey(s.getId());
			}
			//	throw new BDException(storeFreecharges.get(0).getTitle()+"活动免单优惠券使用中，请删除后再删除优惠券！");
		}
		if (ticket.getRangeType() == null) {
			ticketMapper.updateByNull(ticket);
		}
		if (ValidateUtil.isEmptyString(ticket.getUsableTeam())) {
			ticketMapper.updateByNullByUsableTeam(ticket);
		}
		return ticketMapper.updateByPrimaryKeySelective(ticket);
	}

	@Override
	public PageUtils<TicketRecord> listRecords(Long centreId, String queryItem, Integer status, Long ticketId, Long judge, int offset, int limit) {
		PageUtils<TicketRecord> pageUtils = new PageUtils<>();
		Map<String, Object> params = new HashMap<>(4);
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		if (status != null) {
			params.put("status", status);
		}
		if (ticketId != null) {
			params.put("ticketId", ticketId);
		}
		if (judge != null) {
			params.put("judge", judge);
		}
		int total = ticketRecordMapper.countByParams(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(ticketRecordMapper.listByParams(params, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	public PageUtils<TicketRecord> listRecords(String ticketType, Long centreId, String queryItem, Integer status, Long ticketId, Long judge, int offset, int limit) {
		PageUtils<TicketRecord> pageUtils = new PageUtils<>();
		Map<String, Object> params = new HashMap();
		if (ticketType != null) {
			params.put("ticketType", ticketType);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		if (status != null) {
			params.put("status", status);
		}
		if (ticketId != null) {
			params.put("ticketId", ticketId);
		}
		if (judge != null) {
			params.put("judge", judge);
		}
		int total = ticketRecordMapper.countByParams(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(ticketRecordMapper.listByParams(params, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int sendTicket(TicketRecord record) {

		if (record == null || record.getMid() == null) {
			return 0;
		}

		Long ticketId = record.getTicketId();
		if (ticketId == null) {
			return 0;
		}
		Ticket ticket = ticketMapper.selectByPrimaryKey(ticketId);
		if (ticket == null) {
			logger.info("not found ticket by id:{}", ticketId);
			return 0;
		}
		Member member = memberService.getByKey(record.getMid());
		if (member == null) {
			logger.info("member is null:{}", record.getMid());
			return 0;
		}
		if (ticket.getCentreId() != null && !ticket.getCentreId().equals(member.getCentreId())) {
			throw new BDException("该优惠券不是此站点优惠券,不能发放!");
		}

		if (record.getIsFreeCharge() == null || record.getIsFreeCharge() != 1) {
			if (ticket.getStock() < 1) {
				logger.error(BusinessCode.TICKET_SEND_OVER_ERROR.getMsg());
				throw new BDException(BusinessCode.TICKET_SEND_OVER_ERROR);
			}
			if (record.getNum() > ticket.getStock()) {
				logger.error(BusinessCode.TICKET_SEND_LIMIT_ERROR.getMsg());
				throw new BDException(BusinessCode.TICKET_SEND_LIMIT_ERROR);
			}

			int sendedNum = ticketRecordMapper.countMidTicket(record.getMid(), ticketId);
			if (sendedNum >= ticket.getLimit()) {
				logger.error(BusinessCode.TICKET_SEND_LIMIT_ERROR.getMsg() + "===" + ticketId);
				throw new BDException(BusinessCode.TICKET_SEND_LIMIT_ERROR);
			}

			if ((record.getNum() + sendedNum) > ticket.getLimit()) {
				record.setNum(ticket.getLimit() - sendedNum);
			}
		}


		Date now = new Date();
		record.setGetTime(now);
		record.setStartTime(ticket.getStartTime());
		record.setEndTime(ticket.getEndTime());
		//只有在大礼包套装里面，才会使用到这个父ID
		record.setParentId(record.getParentId());
		record.setCount(ticket.getCount() == null || ticket.getCount() == 0 ? 1 : ticket.getCount());
		record.setCountUsed(0);
		if (record.getTeamId() == null) {
			record.setTeamId(ticket.getTeamId());
		}
		record.setCentreId(ticket.getCentreId());


		if (ticket.getType().equals(TicketType.CAMILO.getCode())) {
			//查询旅游码
			TourNumber tourNumber = new TourNumber();
			tourNumber.setStatus(0);
			tourNumber.setCentreId(ticket.getCentreId());
			//tourNumber.setTeamId(ticket.getTeamId());
			TourNumber tourNumberResult = tourNumberMapper.findOne(tourNumber);
			if (tourNumberResult != null) {
				record.setCardNumber(tourNumberResult.getCode());
				record.setPassword(tourNumberResult.getPassword());
				record.setCount(1);
				tourNumberResult.setStatus(1);
				tourNumberMapper.updateByPrimaryKeySelective(tourNumberResult);
			} else {
				return 0;
			}
		}

		if (ticket.getEndTime() == null && ticket.getPeriod() != null) {
			record.setEndTime(DateUtils.getAddDayDate(now, ticket.getPeriod()));
		}
		logger.info("大礼包优惠券回调record：" + JSONObject.toJSONString(record));
		if (record.getTicketType() != null && (record.getTicketType() == TicketRecordType.GIFT_PACKAGE_SUB.getType()
				|| record.getTicketType() == TicketRecordType.GIFT_PACKAGE.getType())) {
			ticketRecordMapper.insertSelective(record);
		} else {
			int num = record.getNum();
			for (int i = 0; i < num; i++) {
				record.setNum(1);
				ticketRecordMapper.insertSelective(record);
			}
//			record.setCount(record.getNum());
//			record.setNum(1);
//			ticketRecordMapper.insertSelective(record);
		}

		ticket.setStock(ticket.getStock() - record.getNum());
		return ticketMapper.updateByPrimaryKeySelective(ticket);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int sendNewMemberTicket(Long mid, Long centreId, Integer num) {
		if (mid == null) {
			return 0;
		}
		if (num == null) {
			num = 1;
		}
		TicketExample te = new TicketExample();
		TicketExample.Criteria criteria = te.createCriteria();
		criteria.andIsInvalidEqualTo(0);
		criteria.andDelEqualTo(0);
		criteria.andRangeTypeEqualTo(TicketRange.RANGE_NEW_MEMBER.getCode());
		criteria.andStockGreaterThanOrEqualTo(num);
		criteria.andCentreIdEqualTo(centreId);
		te.setOrderByClause("create_time desc");
		List<Ticket> list = ticketMapper.selectByExample(te, new RowBounds(0, 1));

		if (CollectionUtils.isEmpty(list)) {
			logger.info("send new member ticket failed!, not found tickets!");
			return 0;
		}
		Ticket ticket = list.get(0);
		TicketRecord tr = new TicketRecord();
		tr.setTicketId(ticket.getId());
		tr.setMid(mid);
		Date now = new Date();
		tr.setStartTime(now);
		tr.setEndTime(ticket.getEndTime());
		if (ticket.getPeriod() != null) {
			tr.setEndTime(DateUtils.getAddDayDate(now, ticket.getPeriod()));
		}
		tr.setGetTime(now);
		tr.setNum(1);
		tr.setCentreId(ticket.getCentreId());
		for (int i = 0; i < num; i++) {
			ticketRecordMapper.insertSelective(tr);
		}
		ticket.setStock(ticket.getStock() - num);
		return ticketMapper.updateByPrimaryKeySelective(ticket);
	}

	@Override
	public int disableRecord(Long recordId) {
		if (recordId == null) {
			return 0;
		}
		TicketRecord record = new TicketRecord();
		record.setId(recordId);
		record.setStatus(-1);
		return ticketRecordMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int checkTicket() {
		List<TicketRecord> ticketRecordList = ticketRecordMapper.getInvalidationTicketRecordlist();
		for (TicketRecord ticketRecord : ticketRecordList) {

			//修改用户优惠券状态
			ticketRecord.setStatus(-1);
			ticketRecordMapper.updateByPrimaryKeySelective(ticketRecord);
			//修改优惠券状态
			Ticket ticket = new Ticket();
			ticket.setId(ticketRecord.getTicketId());
			ticket.setIsInvalid(1);
			ticketMapper.updateByPrimaryKeySelective(ticket);
			Member member = memberService.getByKey(ticketRecord.getMid());
			//发送文本通知
			String content = "优惠券到期提醒：" + "\n";
			if (ValidateUtil.isNotEmptyString(member.getOpenid())) {
				content = content + "\n" + ticketRecord.getTicketName() + "优惠券未使用已到期！" + templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/user/card-package";
				content += "失效日期:" + DateUtil.convertDateToString(ticketRecord.getEndTime(), DateUtil.yyyy_MM_dd_HH_mm_ss) + ";\n";
				logger.info("聚合支付赠送优惠券到期公众号文本消息发送------------------");
				WxNotifyParam notifyParam = new WxNotifyParam();
				notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEXT.getType());//文本消息
				notifyParam.setCenterId(member.getCentreId());
				notifyParam.setGzhOpenId(member.getOpenid());
				notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
				notifyParam.setContent(content);
				notifyParam.setUrl(templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/user/card-package");
				wxNotifyService.sendNotify(notifyParam);

				logger.info("聚合支付赠送优惠券到期小程序文本消息发送------------------");
				WxNotifyParam notifyParam1 = new WxNotifyParam();
				notifyParam1.setMessageType(WxMessageType.MESSAGE_TYPE_TEXT.getType());//文本消息
				notifyParam1.setCenterId(member.getCentreId());
				notifyParam1.setGzhOpenId(member.getOpenid());
				notifyParam1.setTeminal(WxTerminal.TERMINAL_XCX.getTerminal());
				notifyParam1.setContent(content);
				notifyParam1.setUrl(templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/user/card-package");
				wxNotifyService.sendNotify(notifyParam1);

			}
		}
		ticketRecordMapper.checkTicketRecord();
		return ticketMapper.checkTicket();
	}


	@Override
	public int sendTicketOvertimeMessage() {
		Date nowTime = new Date();

		Map<String, Object> params1 = new HashMap<>();
		String afterTwo = DateUtil.convertDateToStr(DateUtils.getAddDayDate(nowTime, 2), DateUtil.yyyy_MM_dd_HH_mm_ss);
		String afterThree = DateUtil.convertDateToStr(DateUtils.getAddDayDate(nowTime, 3), DateUtil.yyyy_MM_dd_HH_mm_ss);
		params1.put("startTime", afterTwo);
		params1.put("overTime", afterThree);
		List<TicketRecord> list1 = ticketRecordMapper.listByParamsByTime(params1);
		int num3 = 0;
		for (TicketRecord ticketRecord : list1) {
			Ticket ticket = ticketMapper.selectByPrimaryKey(ticketRecord.getTicketId());
			if (ValidateUtil.isEmptyObjectOrString(ticket) || ValidateUtil.isEmptyObjectOrString(ticket.getTicketName())) {
				ticket = new Ticket();
				ticket.setTicketName("残留数据");
			}
			Long centreId = ticketRecord.getCentreId();
			Long mid = ticketRecord.getMid();

			Map<String, String> map1 = new HashMap<>();
			map1.put("loggerInfo", "优惠券三日到期提醒发送------------------");
			String content = "您的优惠券还有三天到期!" + "\n";
			content += "优惠券名:" + ticket.getTicketName() + ";\n";
			content += "失效期限:" + DateUtil.convertDateToString(ticket.getEndTime(), DateUtil.yyyy_MM_dd_HH_mm_ss) + ";\n";
			content += "剩余时间:" + "少于3天" + ";\n";
			map1.put("content", content);
			String url = null;
			orderService.sendGZHTicketOverTime(centreId, mid, map1, url);

			Map<String, String> map2 = new HashMap<>();
			map2.put("ticketName", ticket.getTicketName());
			map2.put("endTime", ticketRecord.getEndTime().toString());
			map2.put("remark", "进入小程序查看详情......");
			map2.put("overTime", "少于3天");
			orderService.sendTicketOverTime(centreId, mid, map2);
			num3++;
		}

		Map<String, Object> params2 = new HashMap<>();
		String afterSix = DateUtil.convertDateToStr(DateUtils.getAddDayDate(nowTime, 6), DateUtil.yyyy_MM_dd_HH_mm_ss);
		String afterSeven = DateUtil.convertDateToStr(DateUtils.getAddDayDate(nowTime, 7), DateUtil.yyyy_MM_dd_HH_mm_ss);
		params2.put("startTime", afterSix);
		params2.put("overTime", afterSeven);
		List<TicketRecord> list2 = ticketRecordMapper.listByParamsByTime(params2);
		int num7 = 0;
		for (TicketRecord ticketRecord : list2) {
			Ticket ticket = ticketMapper.selectByPrimaryKey(ticketRecord.getTicketId());
			if (ValidateUtil.isEmptyObjectOrString(ticket) || ValidateUtil.isEmptyObjectOrString(ticket.getTicketName())) {
				ticket = new Ticket();
				ticket.setTicketName("残留数据");
			}
			Long centreId = ticketRecord.getCentreId();
			Long mid = ticketRecord.getMid();
			Map<String, String> map = new HashMap<>();
			map.put("loggerInfo", "优惠券七日到期提醒发送------------------");
			String content = "您的优惠券还有一周到期!" + "\n";
			content += "优惠券名:" + ticket.getTicketName() + ";\n";
			content += "失效期限:" + DateUtil.convertDateToString(ticket.getEndTime(), DateUtil.yyyy_MM_dd_HH_mm_ss) + ";\n";
			content += "剩余时间:" + "少于7天" + ";\n";
			map.put("content", content);
			String url = null;
			orderService.sendGZHTicketOverTime(centreId, mid, map, url);

			Map<String, String> map2 = new HashMap<>();
			map2.put("ticketName", ticket.getTicketName());
			map2.put("endTime", ticketRecord.getEndTime().toString());
			map2.put("remark", "进入小程序查看详情......");
			map2.put("overTime", "少于7天");
			orderService.sendTicketOverTime(centreId, mid, map2);
			num7++;
		}

		Map<String, Object> params3 = new HashMap<>();
		String afterfourteen = DateUtil.convertDateToStr(DateUtils.getAddDayDate(nowTime, 14), DateUtil.yyyy_MM_dd_HH_mm_ss);
		String afterFifteen = DateUtil.convertDateToStr(DateUtils.getAddDayDate(nowTime, 15), DateUtil.yyyy_MM_dd_HH_mm_ss);
		params3.put("startTime", afterfourteen);
		params3.put("overTime", afterFifteen);
		List<TicketRecord> list3 = ticketRecordMapper.listByParamsByTime(params3);
		int num15 = 0;
		for (TicketRecord ticketRecord : list3) {
			Ticket ticket = ticketMapper.selectByPrimaryKey(ticketRecord.getTicketId());
			if (ValidateUtil.isEmptyObjectOrString(ticket) || ValidateUtil.isEmptyObjectOrString(ticket.getTicketName())) {
				ticket = new Ticket();
				ticket.setTicketName("残留数据");
			}
			Long centreId = ticketRecord.getCentreId();
			Long mid = ticketRecord.getMid();
			Map<String, String> map = new HashMap<>();
			map.put("loggerInfo", "优惠券15日到期提醒发送------------------");
			String content = "您的优惠券还有两周到期!" + "\n";
			content += "优惠券名:" + ticket.getTicketName() + ";\n";
			content += "失效期限:" + DateUtil.convertDateToString(ticket.getEndTime(), DateUtil.yyyy_MM_dd_HH_mm_ss) + ";\n";
			content += "剩余时间:" + "少于15天" + ";\n";
			map.put("content", content);
			String url = null;
			orderService.sendGZHTicketOverTime(centreId, mid, map, url);

			Map<String, String> map2 = new HashMap<>();
			map2.put("ticketName", ticket.getTicketName());
			map2.put("endTime", ticketRecord.getEndTime().toString());
			map2.put("remark", "进入小程序查看详情......");
			map2.put("overTime", "少于15天");
			orderService.sendTicketOverTime(centreId, mid, map2);
			num15++;
		}

		Map<String, Object> params4 = new HashMap<>();
		String afterNow = DateUtil.convertDateToStr(nowTime, DateUtil.yyyy_MM_dd_HH_mm_ss);
		String afterOne = DateUtil.convertDateToStr(DateUtils.getAddDayDate(nowTime, 1), DateUtil.yyyy_MM_dd_HH_mm_ss);
		params4.put("startTime", afterNow);
		params4.put("overTime", afterOne);
		List<TicketRecord> list4 = ticketRecordMapper.listByParamsByTime(params4);
		int num1 = 0;
		for (TicketRecord ticketRecord : list4) {
			Ticket ticket = ticketMapper.selectByPrimaryKey(ticketRecord.getTicketId());
			if (ValidateUtil.isEmptyObjectOrString(ticket) || ValidateUtil.isEmptyObjectOrString(ticket.getTicketName())) {
				ticket = new Ticket();
				ticket.setTicketName("残留数据");
			}
			Long centreId = ticketRecord.getCentreId();
			Long mid = ticketRecord.getMid();
			Map<String, String> map = new HashMap<>();
			map.put("loggerInfo", "优惠券1日到期提醒发送------------------");
			String content = "您的优惠券即将到期!" + "\n";
			content += "优惠券名:" + ticket.getTicketName() + ";\n";
			content += "失效期限:" + DateUtil.convertDateToString(ticket.getEndTime(), DateUtil.yyyy_MM_dd_HH_mm_ss) + ";\n";
			content += "剩余时间:" + "少于1天" + ";\n";
			map.put("content", content);
			String url = null;
			orderService.sendGZHTicketOverTime(centreId, mid, map, url);

			Map<String, String> map2 = new HashMap<>();
			map2.put("ticketName", ticket.getTicketName());
			map2.put("endTime", ticketRecord.getEndTime().toString());
			map2.put("remark", "进入小程序查看详情......");
			map2.put("overTime", "少于1天");
			orderService.sendTicketOverTime(centreId, mid, map2);
			num1++;
		}

		return num3 + num7 + num15 + num1;
	}


	@Override
	public List<TicketRecord> getTicketRecords(OrderReq req, List<Long> productGradeIds) {
		Long mid = req.getMemberId();
		List<MemberCartVo> ops = req.getProducts();
		Long teamId = req.getTeamId();
//		Long industryBrandId = req.getIndustryBrandId();
		Long productGradeId = req.getProductGradeId();

		List<TicketRecord> trds = new ArrayList<>();
		List<TicketRecord> tList = new ArrayList<>();
		List<TicketRecord> tList2 = new ArrayList<>();
		if (mid == null || CollectionUtils.isEmpty(ops)) {
			return null;
		}
		//门店行业id
		Long industryId = 0L;
		Long industryBrandId = null;
		Member teamShop = memberService.getByKey(teamId);
		if (teamShop != null) {
			industryId = teamShop.getIndustryId();
			industryBrandId = teamShop.getIndustryBrandId();
		}

		BigDecimal totalOrderPrice = new BigDecimal(0);
		for (MemberCartVo op : ops) {
			if (op == null || op.getMarketprice() == null) {
				continue;
			}
			totalOrderPrice = totalOrderPrice.add(op.getMarketprice().multiply(new BigDecimal(op.getTotal())));
		}
		Map<String, Object> params1 = new HashMap<>(4);
		//params1.put("orderPrice", totalOrderPrice);
		params1.put("mid", mid);
		//params1.put("teamId", teamId);
		params1.put("available", true);
		//params1.put("centreId", null);

		params1.put("industryId", industryId);
//		params1.put("industryBrandId", industryBrandId);

		if (productGradeId != null) {
			params1.put("productGradeId", productGradeId);
		}
		if (productGradeIds != null && productGradeIds.size() > 0) {
			params1.put("productGradeIds", productGradeIds);
		}


		List<TicketRecord> list = ticketRecordMapper.getTicketRecords(params1);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		for (TicketRecord ticketRecord : list) {

			Ticket ticket = ticketMapper.selectByPrimaryKey(ticketRecord.getTicketId());
			if (ticket != null) {
				//优惠券行业id
				Long ticketIndustryId = ticket.getIndustryId();
				Long ticketIndustryBrandId = ticket.getIndustryBrandId();
				if (ticketIndustryId != null) {
					if (ticketIndustryBrandId != null) {
						if (!ticketIndustryBrandId.equals(industryBrandId)) {
							continue;
						}
					} else {
						if (!ticketIndustryId.equals(industryId)) {
							continue;
						}
					}
				}
//				industryId

				ticketRecord.setType(ticket.getType());
				ticketRecord.setRangeType(ticket.getRangeType());

				//指定的商品id分割
				if (ValidateUtil.isNotEmptyString(ticket.getProductId())) {
					String[] productIdArray = ticket.getProductId().split(",");

					if (productIdArray.length > 0) {
						String productName = "";
						for (int i = 0; i < productIdArray.length; i++) {
							ProductCentre productCentre = productCentreMapper.getByKey(Long.valueOf(productIdArray[i]));
							if (productCentre != null) {
								if (ValidateUtil.isNotEmptyString(productName)) {
									productName = productName + "," + productCentre.getTitle();
								} else {
									productName = productName + productCentre.getTitle();
								}
							}
						}
						ticketRecord.setProductName(productName);
					}
				}

				if (ticket.getPcate() != null) {
					Category category = categoryService.getByKey(ticket.getPcate());
					if (category != null) {
						ticketRecord.setPcateName(category.getName());
					}
				}
				if (ticket.getCcate() != null) {
					Category category = categoryService.getByKey(ticket.getCcate());
					if (category != null) {
						ticketRecord.setCcateName(category.getName());
					}
				}
			}

			if (TicketType.SINGLE_COUPON.getCode() == ticketRecord.getType()) {
				tList.add(ticketRecord);
			} else {
				if (ticketRecord.getCondition().compareTo(totalOrderPrice.intValue()) <= 0) {
					tList.add(ticketRecord);
				}
			}

		}
		if (CollectionUtils.isNotEmpty(tList)) {
			setTicketRecord(tList, ops, totalOrderPrice, trds);
		}
		List<Long> centres = ops.stream().map(MemberCartVo::getCentreId).distinct().collect(Collectors.toList());
		//List<Centre> centres = centreService.listAllCentres();
		if (CollectionUtils.isEmpty(centres)) {
			logger.info("not found centre info! auto check order delivery end...");
			return null;
		}
		return trds;
	}

	@Override
	public List<TicketRecord> getDetermineTicketRecords(Long mid, List<MemberCartVo> ops, Long teamId, Long industryBrandId, Long productGradeId, Long industryId) {
		List<TicketRecord> trds = new ArrayList<>();
		List<TicketRecord> tList = new ArrayList<>();
		List<TicketRecord> tList2 = new ArrayList<>();
		if (mid == null || CollectionUtils.isEmpty(ops)) {
			return null;
		}

		BigDecimal totalOrderPrice = new BigDecimal(0);
		for (MemberCartVo op : ops) {
			if (op == null || op.getMarketprice() == null) {
				continue;
			}
			totalOrderPrice = totalOrderPrice.add(op.getMarketprice().multiply(new BigDecimal(op.getTotal())));
		}
		Map<String, Object> params1 = new HashMap<>(4);
		//params1.put("orderPrice", totalOrderPrice);
		params1.put("mid", mid);
		//params1.put("teamId", teamId);
		params1.put("available", true);
		//params1.put("centreId", null);

		if (industryBrandId != null) {
			params1.put("industryBrandId", industryBrandId);
		}
		if (productGradeId != null) {
			params1.put("productGradeId", productGradeId);
		}
		if (industryId != null) {
			params1.put("industryId", industryId);
		}
		List<TicketRecord> list = ticketRecordMapper.getDetermineTicketRecords(params1);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}

		for (TicketRecord ticketRecord : list) {

			Ticket ticket = ticketMapper.selectByPrimaryKey(ticketRecord.getTicketId());
			if (ticket != null) {
				ticketRecord.setType(ticket.getType());
				ticketRecord.setRangeType(ticket.getRangeType());

				//指定的商品id分割
				if (ValidateUtil.isNotEmptyString(ticket.getProductId())) {
					String[] productIdArray = ticket.getProductId().split(",");

					if (productIdArray.length > 0) {
						String productName = "";
						for (int i = 0; i < productIdArray.length; i++) {
							ProductCentre productCentre = productCentreMapper.getByKey(Long.valueOf(productIdArray[i]));
							if (productCentre != null) {
								if (ValidateUtil.isNotEmptyString(productName)) {
									productName = productName + "," + productCentre.getTitle();
								} else {
									productName = productName + productCentre.getTitle();
								}
							}
						}
						ticketRecord.setProductName(productName);
					}
				}

				if (ticket.getPcate() != null) {
					Category category = categoryService.getByKey(ticket.getPcate());
					if (category != null) {
						ticketRecord.setPcateName(category.getName());
					}
				}
				if (ticket.getCcate() != null) {
					Category category = categoryService.getByKey(ticket.getCcate());
					if (category != null) {
						ticketRecord.setCcateName(category.getName());
					}
				}
			}

			if (TicketType.SINGLE_COUPON.getCode() == ticketRecord.getType()) {
				tList.add(ticketRecord);
			} else {
				if (ticketRecord.getCondition().compareTo(totalOrderPrice.intValue()) <= 0) {
					tList.add(ticketRecord);
				}
			}

		}
		if (CollectionUtils.isNotEmpty(tList)) {
			setTicketRecord(tList, ops, totalOrderPrice, trds);
		}
		List<Long> centres = ops.stream().map(MemberCartVo::getCentreId).distinct().collect(Collectors.toList());
		//List<Centre> centres = centreService.listAllCentres();
		if (CollectionUtils.isEmpty(centres)) {
			logger.info("not found centre info! auto check order delivery end...");
			return null;
		}

//		for (Long centre : centres) {
//			List<MemberCartVo> collect = ops.stream().filter(MemberCartVo -> MemberCartVo.getCentreId().toString().equals(centre.toString())).collect(Collectors.toList());
//			if (CollectionUtils.isEmpty(collect)) {
//				continue;
//			}
//			BigDecimal orderPrice = new BigDecimal(0);
//			for (MemberCartVo op : collect) {
//				if (op == null || op.getMarketprice() == null) {
//					continue;
//				}
//				orderPrice = orderPrice.add(op.getMarketprice().multiply(new BigDecimal(op.getTotal())));
//			}
//			for (TicketRecord ticketRecord : list) {
//				if (centre.equals(ticketRecord.getCentreId()) && ticketRecord.getCondition().compareTo(orderPrice.intValue()) <= 0) {
//					tList2.add(ticketRecord);
//				}
//
//			}
//			if (CollectionUtils.isNotEmpty(tList2)) {
//				setTicketRecord(tList2, collect, totalOrderPrice, trds);
//			}
//
//			/**
//			 Map<String,Object> params = new HashMap<>(4);
//			 params.put("orderPrice", orderPrice);
//			 params.put("mid", mid);
//			 params.put("centreId", centre.getCentreId());
//			 List<TicketRecord> list1 = ticketRecordMapper.getTicketRecords(params);
//			 */
//
//		}

		return trds;
	}

	public void setTicketRecord(List<TicketRecord> list1, List<MemberCartVo> ops, BigDecimal orderPrice, List<TicketRecord> trds) {
		//得到所有商品
		Map<String, ProductCentre> pcMap = new HashMap<String, ProductCentre>();
		//得到所有商品
		for (MemberCartVo op : ops) {
			if (op == null || op.getProductId() == null) {
				continue;
			}
			ProductCentre product = productCentreMapper.getByKey(op.getProductId());
			pcMap.put(op.getProductId().toString().trim(), product);
		}

		for (TicketRecord tr : list1) {

			Ticket ticket = ticketMapper.selectByPrimaryKey(tr.getTicketId());
			if (ticket == null) {
				continue;
			}
			if (ticket.getStartTime().getTime() > new Date().getTime()) {
				continue;
			}

			boolean mz = false;
			for (MemberCartVo op : ops) {
				if (op == null || op.getProductId() == null) {
					continue;
				}

				Integer rangType = ticket.getRangeType();
				//限分类
				if (Objects.equals(rangType, TicketRange.RANGE_CATEGORY.getCode())) {
					//ProductCentre pc = productCentreMapper.getByKey(op.getProductId());
					ProductCentre pc = pcMap.get(op.getProductId().toString().trim());
					if (pc == null) {
						continue;
					}
					if (ticket.getPcate() != null && Objects.equals(pc.getPcate(), ticket.getPcate())) {
						if (ticket.getCcate() == null || ticket.getCcate() == 0) {
							//价格
							BigDecimal price = new BigDecimal("0");

							for (String key : pcMap.keySet()) {
								//循环订单所有商品并判断商品是否包含这个分类
								if (Objects.equals(pcMap.get(key).getPcate(), ticket.getPcate())) {
									//得到这个对象下面的订单用户信息
									List<MemberCartVo> memList = ops.stream().filter(MemberCartVo ->
											MemberCartVo.getProductId().toString().trim().equals(key)
									).collect(Collectors.toList());

									//价格累加 商品价格乘以购买数量
									price = price.add(pcMap.get(key).getMarketprice().multiply(new BigDecimal(memList.get(0).getTotal())));
								}
							}
							//价格大于等于优惠券满足条件
							if (TicketType.SINGLE_COUPON.getCode() == ticket.getType()) {
								mz = true;
							} else {
								if (price.compareTo(ticket.getCondition()) >= 0) {
									mz = true;
								}
							}
							break;
						}
					}
					if (ticket.getCcate() != null && Objects.equals(pc.getCcate(), ticket.getCcate())) {
						//价格
						BigDecimal price = new BigDecimal("0");
						for (String key : pcMap.keySet()) {
							//循环订单所有商品并判断商品是否包含这个分类
							if (Objects.equals(pcMap.get(key).getCcate(), ticket.getCcate())) {
								//得到这个对象下面的订单用户信息
								List<MemberCartVo> memList = ops.stream().filter(MemberCartVo ->
										MemberCartVo.getProductId().toString().trim().equals(key)
								).collect(Collectors.toList());

								//价格累加 商品价格乘以购买数量
								price = price.add(pcMap.get(key).getMarketprice().multiply(new BigDecimal(memList.get(0).getTotal())));
							}
						}
						//价格大于等于优惠券满足条件
						if (TicketType.SINGLE_COUPON.getCode() == ticket.getType()) {
							mz = true;
						} else {
							if (price.compareTo(ticket.getCondition()) >= 0) {
								mz = true;
							}
						}
						break;
					}
				} else if (Objects.equals(rangType, TicketRange.RANGE_PRODUCT.getCode())) {
					//限商品
					if (StringUtils.isNotEmpty(ticket.getProductId())) {
						if (ticket.getProductId().contains(String.valueOf(op.getProductId()))) {
							//价格
							BigDecimal price = new BigDecimal("0");
							for (String key : pcMap.keySet()) {
								//循环订单所有商品并判断商品是否包含这个商品
								if (ticket.getProductId().contains(key)) {
									//得到这个对象下面的订单用户信息
									List<MemberCartVo> memList = ops.stream().filter(MemberCartVo ->
											MemberCartVo.getProductId().toString().trim().equals(key)
									).collect(Collectors.toList());

									//价格累加 商品价格乘以购买数量
									price = price.add(pcMap.get(key).getMarketprice().multiply(new BigDecimal(memList.get(0).getTotal())));
								}
							}
							if (TicketType.SINGLE_COUPON.getCode() == ticket.getType()) {
								mz = true;
							} else {
								//价格大于等于优惠券满足条件
								if (price.compareTo(ticket.getCondition()) >= 0) {
									mz = true;
								}
							}
							break;
						}
					}

				} else {
					mz = true;
					break;
				}
			}
			if (!mz) {
				continue;
			}

			BigDecimal amount = tr.getAmount();
			Integer type = tr.getType();
			if (amount == null || type == null) {
				continue;
			}
			if (TicketType.VOUCHER.getCode() == type) {
				tr.setDeductAmount(amount);
			} else {
				tr.setDeductAmount(amount.multiply(orderPrice).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP));
			}
			trds.add(tr);
		}
	}


	@Override
	public List<TicketRecord> getTicketRecordsJuHe(Long mid, String payMoney, Long teamId) {
		List<TicketRecord> trds = new ArrayList<>();

		BigDecimal totalOrderPrice = new BigDecimal(payMoney);

		Map<String, Object> params1 = new HashMap<>(4);
		//params1.put("orderPrice", totalOrderPrice);
		params1.put("mid", mid);
		params1.put("teamId", teamId);
		params1.put("available", true);
		params1.put("juhePay", true);
		List<TicketRecord> list = ticketRecordMapper.getTicketRecords(params1);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		for (TicketRecord ticketRecord : list) {
			Ticket ticket = ticketMapper.selectByPrimaryKey(ticketRecord.getTicketId());
			if(ticket != null){
				if (TicketType.SINGLE_COUPON.getCode() == ticket.getType()) {
					trds.add(ticketRecord);
				} else if (TicketType.COUPON.getCode() == ticket.getType() || TicketType.VOUCHER.getCode() == ticket.getType()) {
					if (ticketRecord.getCondition().compareTo(totalOrderPrice.intValue()) <= 0) {
						trds.add(ticketRecord);
					}
				}
			}
		}

		return trds;
	}

	@Override
	public PageUtils<TicketRecord> listMidRecords(Long mid, Integer type, Integer status, Long industryBrandId, Long productGradeId, Long industryId, int offset, int limit) {
		PageUtils<TicketRecord> pageUtils = new PageUtils<>();
		Map<String, Object> params = new HashMap<>(4);
		if (mid != null) {
			params.put("mid", mid);
		}

		if (status != null) {
			params.put("status", status);
		}

		if (type != null) {
			params.put("ticketType", type);
			if (type == 2) {
				params.put("isSub", 1);
			}
		}
		if (industryBrandId != null) {
			params.put("industryBrandId", industryBrandId);
		}
		if (productGradeId != null) {
			params.put("productGradeId", productGradeId);
		}
		if (industryId != null) {
			params.put("industryId", industryId);
		}
		Member member = memberService.getByKey(mid);
		params.put("centreId", member.getCentreId());
		int total = ticketRecordMapper.countByParams(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			List<TicketRecord> ticketRecords = ticketRecordMapper.listByParams(params, new RowBounds(offset, limit));
			List<TicketRecord> newLsit = new ArrayList<>();
			if (ValidateUtil.isNotEmptyCollection(ticketRecords)) {
				//统计每个门店
				for (TicketRecord subTicketRecord : ticketRecords) {
					Ticket ticket = ticketMapper.selectByPrimaryKey(subTicketRecord.getTicketId());
					if (ticket != null) {
						subTicketRecord.setType(ticket.getType());
						subTicketRecord.setRangeType(ticket.getRangeType());

						if (ValidateUtil.isNotEmptyString(ticket.getProductId())) {
							//指定的商品id分割
							String[] productIdArray = ticket.getProductId().split(",");

							if (productIdArray.length > 0) {
								String productName = "";
								for (int i = 0; i < productIdArray.length; i++) {
									ProductCentre productCentre = productCentreMapper.getByKey(Long.valueOf(productIdArray[i]));
									if (productCentre != null) {
										if (ValidateUtil.isNotEmptyString(productName)) {
											productName = productName + "," + productCentre.getTitle();
										} else {
											productName = productName + productCentre.getTitle();
										}
									}
								}
								subTicketRecord.setProductName(productName);
							}
						}

						if (ticket.getPcate() != null) {
							Category category = categoryService.getByKey(ticket.getPcate());
							if (category != null) {
								subTicketRecord.setPcateName(category.getName());
							}
						}
						if (ticket.getCcate() != null) {
							Category category = categoryService.getByKey(ticket.getCcate());
							if (category != null) {
								subTicketRecord.setCcateName(category.getName());
							}
						}
					}

					//礼包优惠券，需要查询子券
					if (subTicketRecord.getTicketType() == 1) {
						params = new HashMap<>();
						params.put("parentId", subTicketRecord.getId());
						params.put("isSub", 1);
						List<TicketRecord> subTicketRecords = ticketRecordMapper.listByParams(params, new RowBounds(offset, limit));
						if (ValidateUtil.isNotEmptyCollection(subTicketRecords)) {
							Map<String, Object> subTicketInfo = new HashMap<>();
							for (TicketRecord subTicketRecord2 : subTicketRecords) {
								String key = subTicketRecord2.getTeamId() + StringConstans.STR_EMPTY;
								if (!subTicketInfo.containsKey(key)) {
									subTicketInfo.put(key, new HashMap<>());
								}
								Map<String, Object> subMap = (Map<String, Object>) subTicketInfo.get(key);
								if (!subMap.containsKey("shopInfo")) {
									subMap.put("shopInfo", memberService.getByKey(subTicketRecord2.getTeamId()));
								}
								//优惠券列表添加
								if (!subMap.containsKey("subRecordList")) {
									subMap.put("subRecordList", new ArrayList<TicketRecord>());
								}
								((List) subMap.get("subRecordList")).add(subTicketRecord2);
							}
							subTicketRecord.setSubTicketRecordInfo(subTicketInfo);
						}
					}
					newLsit.add(subTicketRecord);
				}
			}
			pageUtils.setRows(newLsit);
		}
		return pageUtils;
	}

	@Override
	public int updateRecordToNoUse(Long trId) {
		if (trId == null) {
			return 0;
		}
		TicketRecord ticketRecordResult = ticketRecordMapper.getByKeyAllStatus(trId);
		if (ticketRecordResult == null) {
			return 0;
		}
		TicketRecord tr = new TicketRecord();
		tr.setStatus(TicketStatus.NO_USE.getStatus());
		tr.setId(trId);
		tr.setCountUsed(ticketRecordResult.getCountUsed() - 1);
		tr.setOrderId(Long.valueOf("0"));
		return ticketRecordMapper.updateByPrimaryKeySelective(tr);
	}

	@Override
	public int updateRecord(TicketRecord tr) {
		if (tr == null || tr.getId() == null) {
			logger.info("ticket record update not success,lose info or trId!");
			return 0;
		}
		return ticketRecordMapper.updateByPrimaryKeySelective(tr);
	}

	@Override
	public TicketRecord getRecordByKey(Long trId) {
		if (trId == null) {
			return null;
		}
		return ticketRecordMapper.getByKey(trId);
	}

	@Override
	public PageUtils<Map<String, Object>> couponList(Map<String, Object> map, int offset, int limit) {
		PageUtils<Map<String, Object>> pageUtils = new PageUtils<>();

		int total = ticketMapper.countCouponList(map);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(ticketMapper.couponList(map, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveTicketRecords(Ticket ticket, Long mId) {
		TicketRecord tr = new TicketRecord();
		int sendedNum = ticketRecordMapper.countMidTicket(mId, ticket.getId());
		if ((1 + sendedNum) > ticket.getLimit()) {
			throw new BDException(BusinessCode.TICKET_SEND_LIMIT_ERROR);
		}
		tr.setTicketId(ticket.getId());
		tr.setMid(mId);
		tr.setStatus(0);
		tr.setType(ticket.getType());
		Date now = new Date();
		tr.setStartTime(now);
		tr.setEndTime(ticket.getEndTime());
		if (ticket.getPeriod() != null) {
			tr.setEndTime(DateUtils.getAddDayDate(now, ticket.getPeriod()));
		}
		tr.setGetTime(now);
		tr.setNum(1);
		tr.setCentreId(ticket.getCentreId());
		ticketRecordMapper.insertSelective(tr);
		ticket.setStock(ticket.getStock() - 1);
		return ticketMapper.updateByPrimaryKeySelective(ticket);
	}

	@Override
	public Ticket getTicketRanType(int rangeType) {
		return ticketMapper.selTicketRanType(rangeType);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<Ticket> getFirstLoginCoup(String centreid, Long memberid, Long teamId) {


		//获取当前有效期内的新人券
		List<Ticket> ticketVo;
		List<Ticket> ticketVo1 = new ArrayList<Ticket>();
		Map<String, Object> queryMap = new HashMap<>();
		queryMap.put("centreid", centreid);
		queryMap.put("teamId", teamId);
		ticketVo = ticketMapper.setFirstLoginCoup(queryMap);
		if (CollectionUtils.isNotEmpty(ticketVo)) {
			ticketVo1 = new ArrayList<>();
			for (Ticket ticket : ticketVo) {
				if (redisTemplate.hasKey("isNew:" + memberid)) {
					ticketVo1.add(ticket);
				} else {
					if (ticket.getRangeType() == null || ticket.getRangeType() != 1) {
						int i = ticketRecordMapper.countMidTicket(memberid, ticket.getId());
						if (i <= 0) {
							ticketVo1.add(ticket);
						}
					}
				}
			}
		}

		return ticketVo1;
	}

	@Override
	public TicketVo getUncellectCoup(String centreid, String memberid) {
		Map<String, Object> queryMap = new HashMap<>();
		queryMap.put("centreid", centreid);
		queryMap.put("memberid", memberid);
		return ticketMapper.selUncellectCoup(queryMap);
	}

	@Override
	@Transactional
	public void updateRecord(Long memberId, List<String> ticketid) {
		List<TicketRecord> list = new ArrayList<>();
		for (String aLong : ticketid) {
			//获取当前有效期内的券
			Ticket yhticket = ticketMapper.selectByPrimaryKey(Long.valueOf(aLong));
			if (yhticket != null) {
				//查询是否有未领取记录
				Map<String, Object> queryMap1 = new HashMap<>();
				queryMap1.put("memberid", memberId);
				queryMap1.put("ticketid", yhticket.getId());
				List<TicketRecord> selMidTicket1 = ticketRecordMapper.selMemberIdTicket(queryMap1);

				//已经领取过
				if (CollectionUtils.isNotEmpty(selMidTicket1)) {
					throw new BDException(BusinessCode.TICKET_SEND_OVER_ERROR1);
				}

				//生成未领取记录
				TicketRecord ticketRecord = new TicketRecord();
				ticketRecord.setTicketId(yhticket.getId());
				ticketRecord.setMid(memberId);
				ticketRecord.setStartTime(yhticket.getStartTime());
				ticketRecord.setGetTime(new Date());
				ticketRecord.setEndTime(yhticket.getEndTime());
				if (yhticket.getEndTime() == null && yhticket.getPeriod() != null) {
					ticketRecord.setEndTime(DateUtils.getAddDayDate(new Date(), yhticket.getPeriod()));
				}
				ticketRecord.setStatus(0);
				ticketRecord.setNum(1);
				ticketRecord.setCentreId(yhticket.getCentreId());
				ticketRecord.setTicketType(0);
				ticketRecord.setTeamId(yhticket.getTeamId());
				if (yhticket.getType().equals(TicketType.CAMILO.getCode())) {
					//查询旅游码
					TourNumber tourNumber = new TourNumber();
					tourNumber.setStatus(0);
					tourNumber.setCentreId(yhticket.getCentreId());
					//tourNumber.setTeamId(yhticket.getTeamId());
					TourNumber tourNumberResult = tourNumberMapper.findOne(tourNumber);
					if (tourNumberResult == null) {
						//没有旅游码不发放旅游券
						continue;
					}
					ticketRecord.setCardNumber(tourNumberResult.getCode());
					ticketRecord.setPassword(tourNumberResult.getPassword());
					ticketRecord.setCount(1);
					tourNumberResult.setStatus(1);
					tourNumberMapper.updateByPrimaryKeySelective(tourNumberResult);
				}
				list.add(ticketRecord);

			}
		}
		ticketRecordMapper.insertSelectiveBatch(list);
		redisTemplate.delete("isNew:" + memberId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int sendTicketAll(TicketRecord record, Long userCentreId) {
		Long ticketId = record.getTicketId();
		Long centreId = record.getCentreId();
		if (record == null || ticketId == null) {
			return 0;
		}
		//查询优惠券
		Ticket ticket = ticketMapper.selectByPrimaryKey(ticketId);
		if (ticket == null) {
			logger.info("not found ticket by id:{}", ticketId);
			return 0;
		}
		if (ticket.getCentreId() != null && !ticket.getCentreId().equals(record.getCentreId())) {
			throw new BDException("该优惠券不是此站点优惠券,不能发放!");
		}
		if (ticket.getStock() < 1) {
			throw new BDException(BusinessCode.TICKET_SEND_OVER_ERROR);
		}
		if (ticket.getLimit() < record.getNum()) {
			throw new BDException(BusinessCode.TICKET_SEND_LIMIT_ERROR);
		}
		Date now = new Date();

		if (ticket.getPeriod() != null) {
			record.setEndTime(DateUtils.getAddDayDate(now, ticket.getPeriod()));
		}
		//查询该站点下的所有用户
		HashMap<String, Object> req = new HashMap<>();
		req.put("centreId", centreId);
		List<Member> listByWhere2 = memberMapper.getListByWhere2(req);
		List<TicketRecord> ticketRecords = new ArrayList<>();
		TicketRecord ticketRecord;
		for (Member member : listByWhere2) {
			ticketRecord = new TicketRecord();
			ticketRecord.setNum(1);
			ticketRecord.setTicketId(ticket.getId());
			ticketRecord.setMid(member.getId());
			ticketRecord.setGetTime(now);
			ticketRecord.setStartTime(ticket.getStartTime());
			ticketRecord.setEndTime(ticket.getEndTime());
			if (ticket.getEndTime() == null && ticket.getPeriod() != null) {
				ticketRecord.setEndTime(DateUtils.getAddDayDate(now, ticket.getPeriod()));
			}
			ticketRecord.setCentreId(ticket.getCentreId());
			ticketRecord.setTeamId(ticket.getTeamId());
			ticketRecord.setTicketType(0);
			ticketRecord.setStatus(0);
			ticketRecords.add(ticketRecord);
		}
		int num = record.getNum();
		int size = listByWhere2.size();
		if (size * num > ticket.getStock()) {
			throw new BDException(BusinessCode.TICKET_SEND_LIMIT_ERROR);
		}
		for (int i = 0; i < num; i++) {
			ticketRecordMapper.insertSelectiveBatch(ticketRecords);
		}
		ticket.setStock(ticket.getStock() - num * size);
		return ticketMapper.updateByPrimaryKeySelective(ticket);
	}

	@Override
	public void giftPacksTickets(Long activityId) {
		Activity activity = activityMapper.selectByPrimaryKey(activityId);

		ActivityProductExample example = new ActivityProductExample();
		example.createCriteria().andActivityIdEqualTo(activity.getId());
		List<ActivityProduct> activityProductList = activityProductMapper.selectByExample(example);

		//查询大礼包绑定的相关优惠券
		if (ValidateUtil.isNotEmptyCollection(activityProductList)) {
			//旅游券可能送多张
			int camiloCount = 0;
			for (ActivityProduct activityProductTemp : activityProductList) {
				List<StoreFreecharge> storeFreechargeList = null;
				List<String> list = new ArrayList<>();
				if (ValidateUtil.isNotEmptyString(activityProductTemp.getCouponIds())) {
					Collections.addAll(list, activityProductTemp.getCouponIds().split(","));
					storeFreechargeList = storeFreechargeMapper.selectByIdInStoreFreecharge(list);
				}
				if (ValidateUtil.isNotEmptyCollection(storeFreechargeList)) {
					//判断优惠券是否充足
					for (StoreFreecharge storeFreecharge : storeFreechargeList) {
						Ticket ticket = this.getByKey(storeFreecharge.getRefId());
						if (ticket != null) {
							if (ticket.getType().equals(TicketType.CAMILO.getCode())) {
								camiloCount++;
							} else {
								if (ticket.getStock() < 1) {
									throw new BDException("优惠卷已被抢空，请等待商家补充库存");
								}
							}
						} else {
							throw new BDException("优惠卷已被抢空，请等待商家补充库存");
						}
					}
				} else {
					throw new BDException("优惠卷已被抢空，请等待商家补充库存");
				}
			}
			//查询旅游码
			if (camiloCount > 0) {
				TourNumberExample tourNumber = new TourNumberExample();
				tourNumber.createCriteria().andStatusEqualTo(0).andCentreIdEqualTo(activity.getCentreId());
				List<TourNumber> tourNumberResult = tourNumberMapper.selectByExample(tourNumber);
				if (tourNumberResult.size() < camiloCount) {
					throw new BDException("旅游卷已被抢空，请等待商家补充库存");
				}
			}
		} else {
			throw new BDException("优惠卷已被抢空，请等待商家补充库存");
		}
	}

	@Override
	public void groupTickets(Long groupId) {
		MarketingGroup marketingGroup = marketingGroupMapper.getMarketingGroupById(groupId);
		List<TicketDTO> newTicketsList = new ArrayList<>();
		int camiloCount = 0;
		if (GroupTypeEnum.SNAP_UP.getCode().equals(marketingGroup.getType())) {
			int groupCountFailed = marketingGroup.getNeedJoinGroupNum() - marketingGroup.getWinningNumber();
			//抢购失败可能赠送优惠券
			if (marketingGroup.getIsCoupons() == 1 && ValidateUtil.isNotEmptyString(marketingGroup.getTicketIds())) {
				List<TicketDTO> ticketsList = JSONObject.parseArray(marketingGroup.getTicketIds(), TicketDTO.class);
				//将重复券去重 加上数量
				if (ValidateUtil.isNotEmptyCollection(ticketsList)) {
					for (TicketDTO ticketDTO : ticketsList) {
						boolean bol = false;
						for (TicketDTO newTicketDTO : newTicketsList) {
							if (newTicketDTO.getId().equals(ticketDTO.getId())) {
								newTicketDTO.setCount(newTicketDTO.getCount() + groupCountFailed);
								bol = true;
							}
						}
						if (!bol) {
							ticketDTO.setCount(groupCountFailed);
							newTicketsList.add(ticketDTO);
						}
					}
				}
			}
		}

		if (MarketingGroupTypeEnum.GIFT_BAG.getCode().equals(marketingGroup.getMarketingGroupType())) {
			int groupNum = marketingGroup.getNeedJoinGroupNum();
			Long activityId = marketingGroup.getProductId();
			Activity activity = activityMapper.selectByPrimaryKey(activityId);

			ActivityProductExample example = new ActivityProductExample();
			example.createCriteria().andActivityIdEqualTo(activity.getId());
			List<ActivityProduct> activityProductList = activityProductMapper.selectByExample(example);

			//查询大礼包绑定的相关优惠券
			if (ValidateUtil.isNotEmptyCollection(activityProductList)) {
				//旅游券可能送多张
				for (ActivityProduct activityProductTemp : activityProductList) {
					List<StoreFreecharge> storeFreechargeList = null;
					List<String> list = new ArrayList<>();
					if (ValidateUtil.isNotEmptyString(activityProductTemp.getCouponIds())) {
						Collections.addAll(list, activityProductTemp.getCouponIds().split(","));
						storeFreechargeList = storeFreechargeMapper.selectByIdInStoreFreecharge(list);
					}
					if (storeFreechargeList != null) {
						//判断优惠券是否充足
						for (StoreFreecharge storeFreecharge : storeFreechargeList) {
							boolean bol = false;
							for (TicketDTO newTicketDTO : newTicketsList) {
								if (newTicketDTO.getId().equals(storeFreecharge.getRefId())) {
									newTicketDTO.setCount(newTicketDTO.getCount() + groupNum);
									bol = true;
								}
							}
							if (!bol) {
								TicketDTO ticketDTO = new TicketDTO();
								ticketDTO.setId(storeFreecharge.getRefId());
								ticketDTO.setCount(groupNum);
								newTicketsList.add(ticketDTO);
							}

						}
					}
				}
			}
		}

		for (TicketDTO ticketDTO : newTicketsList) {
			Ticket ticket = this.getByKey(ticketDTO.getId());
			if (ticket != null) {
				if (ticket.getType().equals(TicketType.CAMILO.getCode())) {
					camiloCount = camiloCount + ticketDTO.getCount();
				} else {
					if (ticket.getStock() < ticketDTO.getCount()) {
						throw new BDException("优惠卷补贴已无库存，请等待商家补充库存");
					}
				}
			} else {
				throw new BDException("优惠卷补贴已无库存，请等待商家补充库存");
			}
		}

		//查询旅游码
		if (camiloCount > 0) {
			TourNumberExample tourNumber = new TourNumberExample();
			tourNumber.createCriteria().andStatusEqualTo(0).andCentreIdEqualTo(marketingGroup.getCentreId());
			List<TourNumber> tourNumberResult = tourNumberMapper.selectByExample(tourNumber);
			if (tourNumberResult.size() < camiloCount) {
				throw new BDException("旅游卷已无库存，请等待商家补充库存");
			}
		}
	}

	@Override
	public List<Ticket> queryList(Map params) {
		return ticketMapper.queryList(params);
	}

	@Override
	public PageUtils<Ticket> listTickets(String queryItem, Long centreId, Long teamId, Integer status, int offset, int limit) {
		PageUtils<Ticket> pageUtils = new PageUtils<>();

		TicketExample example = new TicketExample();
		TicketExample.Criteria criteria = example.createCriteria();
		if (centreId != null) {
			criteria.andCentreIdEqualTo(centreId);
		}
		if (teamId != null) {
			criteria.andTeamIdEqualTo(teamId);
		}

		if (StringUtils.isNotEmpty(queryItem)) {
			criteria.andTicketNameLike('%' + queryItem + '%');
		}
		if (status != null) {
			criteria.andIsInvalidEqualTo(status);
		}

		criteria.andDelEqualTo(0);

		int total = ticketMapper.countByExample(example);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(ticketMapper.selectByExample(example, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	public PageUtils<TicketRecordUse> listRecordUsers(String ticketType, Long centreId, String queryItem, Integer status, Long ticketId, Long judge, int offset, int limit, Long teamId) {
		PageUtils<TicketRecordUse> pageUtils = new PageUtils<>();
		Map<String, Object> params = new HashMap();
		if (ticketType != null) {
			params.put("ticketType", ticketType);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		if (status != null) {
			params.put("status", status);
		}
		if (ticketId != null) {
			params.put("ticketId", ticketId);
		}
		if (judge != null) {
			params.put("judge", judge);
		}
		if (teamId != null) {
			params.put("teamId", teamId);
		}
		int total = ticketRecordUseMapper.countByParams(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(ticketRecordUseMapper.listByParams(params, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	public PageUtils<TicketRecord> getLocalLifeCoupon(Long mid, Long ticketRecordId, int offset, int limit) {
		PageUtils<TicketRecord> pageUtils = new PageUtils<>();
		Map<String, Object> params = new HashMap<>(4);
		TicketRecord ticketRecord = null;
		if (ticketRecordId != null) {
			ticketRecord = ticketRecordMapper.getByKeyAllStatus(ticketRecordId);
		}
		if (ticketRecord != null) {
			params.put("teamId", ticketRecord.getTeamId());
			params.put("mid", ticketRecord.getMid());
		} else {
			return pageUtils;
		}

		//礼包子券
		params.put("ticketType", TicketRecordType.GIFT_PACKAGE_SUB.getType());
		params.put("isSub", 1);
		params.put("status", 0);

		int total = ticketRecordMapper.countByParams(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(ticketRecordMapper.listByParams(params, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	public PageUtils<Member> getLocalLifShopCoupon(Long memberId, Integer status, int offset, int limit) {
		PageUtils<Member> pageUtils = new PageUtils<>();
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("memberId", memberId);
		paramMap.put("status", status);
		int total = memberMapper.getLocalLifShopCount(paramMap, new RowBounds(offset, limit));
		pageUtils.setTotal(total);
		List<Member> shopList = memberMapper.getLocalLifShop(paramMap, new RowBounds(offset, limit));
		if (ValidateUtil.isNotEmptyCollection(shopList)) {
			pageUtils.setRows(shopList);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("mid", memberId);
			params.put("status", status);
			//params.put("ticketType", TicketRecordType.GIFT_PACKAGE_SUB.getType());
			for (Member shopMember : shopList) {
				params.put("teamId", shopMember.getId());
				shopMember.setTicketRecords(ticketRecordMapper.getTicketRecords(params));
			}
		}

		return pageUtils;
	}

	@Override
	public PageUtils<Member> getOrderCouponList(Long orderId, int offset, int limit) {
		PageUtils<Member> pageUtils = new PageUtils<>();
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("orderId", orderId);
		int total = memberMapper.getLocalLifShopCount(paramMap, new RowBounds(offset, limit));
		pageUtils.setTotal(total);
		List<Member> shopList = memberMapper.getLocalLifShop(paramMap, new RowBounds(offset, limit));
		if (ValidateUtil.isNotEmptyCollection(shopList)) {
			pageUtils.setRows(shopList);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("orderId", orderId);
			params.put("status", 0);
			params.put("ticketType", TicketRecordType.GIFT_PACKAGE_SUB.getType());
			for (Member shopMember : shopList) {
				params.put("teamId", shopMember.getId());
				shopMember.setTicketRecords(ticketRecordMapper.getTicketRecords(params));
			}
		}

		return pageUtils;
	}
}
